<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增账单')"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-bill-add">

        <div class="form-group">
            <label class="col-sm-3 control-label is-required">消费描述：</label>
            <div class="col-sm-5" th:with="type=${@dict.getType('commodity_management')}">
                <div class="radio" th:each="dict : ${type}">
                    <label class="check-box">
                        <input name="description" th:data-label="${dict.dictLabel}" type="checkbox"
                               th:id="${dict.dictCode}" th:value="${dict.dictValue}"
                               th:text="${dict.dictLabel}">
                    </label>

                    <!--  一个input用来控制数量  -->
                    <input onchange="numberChange()" value="0" type="number"
                           th:id="${dict.dictCode}+'-descriptionNumber'" maxlength="3"
                           style="width: 50px" disabled> 份
                </div>
            </div>
        </div>
        <br>
        <div class="form-group">
            <label class="col-sm-3 control-label"></label>
            <div class="col-sm-5">
                <div class="input-group m-b" style="display: flex">
                    <div>总价:&yen;</div>
                    <div id="total">0</div>
                </div>
                <div class="input-group m-b" style="display: flex">
                    <div>折扣 x </div>
                      <div id="discount" style="color: red">1</div>
                </div>
                <div class="input-group m-b" style="display: flex">
                    <div>实际应付:&yen;</div>
                    <div id="actualPay">0</div>
                </div>
            </div>
        </div>

        <br>
        <div class="form-group">
            <label class="col-sm-3 control-label">支付方式：</label>
            <div class="col-sm-8" th:with="type=${@dict.getType('mode_payment')}">
                <label th:each="dict : ${type}" class="radio-box">
                    <input id="paymentMethod" name="paymentMethod" th:checked="${dict.dictValue}=='1'" type="radio"
                           th:value="${dict.dictValue}" th:text="${dict.dictLabel}">
                </label>
            </div>
        </div>

        <div class="form-group" id="my-customerId">
            <label class="col-sm-3 control-label">会员卡号：</label>
            <select class="col-sm-8" name="customerId" id="customerId" disabled>
                <option value="">----请选择会员----</option>
            </select>



        </div>

        <div class="form-group" style="display: none">
            <div class="input-group m-b">
                <input name="amount" id="amount"/>
            </div>
        </div>
        <div class="form-group" style="display: none">
            <div class="input-group m-b">
                <input name="keyOne" id="keyOne"/>
            </div>
        </div>

        <br>
        <br>
        <br>
        <div class="form-group">
            <label class="col-sm-3 control-label"></label>
            <div class="col-sm-5">
                <button type="button" class="btn btn-w-m btn-primary" onclick="submitAddBill()">提交</button>
            </div>
        </div>
    </form>


</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: select2-css"/>
<th:block th:include="include :: select2-js"/>

<script th:inline="javascript">
    var prefix = ctx + "custom/bill"
    var prefixMember = ctx + "custom/member"
    var discount = 1
    var actualPay = 0


    $("#form-bill-add").validate({
        focusCleanup: true
    });
    // 弹出检查
    function check(rs) {
        if (rs.code === 500) {
            $.modal.msgError("系统错误!,请联系管理员");
        } else if (rs.code === 0) {
            $.modal.msgSuccess("提交成功!");
            // 关闭选项卡
            $.modal.closeTab();
        } else {
            $.modal.msgWarning(rs.message);
        }
    }


    function submitConfirm(){

    }


    //提交表单
    function submitAddBill() {
        var total = parseFloat($('#total').text());
        if (total > 0) {
            //判断如果选会员支付的话是否选择了会员
            var paymentMethod = $('input[name="paymentMethod"]:checked').val();
            if (paymentMethod === "3"||paymentMethod === 3) {
                if ($('#customerId').val() === "" || $('#customerId').val() === null) {
                    $.modal.msgWarning("请先选择会员");
                    return;
                }
            }
            $.modal.confirm("确认提交?",function (){
                //提交
                // 打开遮罩层
                $.modal.loading("正在提交订单，请稍后...");
                $.operate.save(prefix + "/add", $('#form-bill-add').serialize(), function (rs) {
                    // 关闭遮罩层
                    $.modal.closeLoading();
                    check(rs)
                });
            })
        } else {
            $.modal.msgWarning("请先选择消费项目");
        }
    }


    // 选择现金还是微信
    $("input[name = paymentMethod]").on('ifChecked', function (obj) {
        var i = $(this).val()
        //如果是3的话就是会员
        if (i === "3" || i===3) {
            $('#customerId').prop('disabled', false); // 启用
        } else {
            $("#customerId").select2("val", [""]);                 // 单个赋值
            $('#customerId').prop('disabled', true); // 禁用

        }
    })

    // 选择会员卡号模糊搜索
    $("#customerId").select2({
        ajax: {
            url: prefixMember + "/listByPhone",
            dataType: 'json',
            delay: 1000,
            data: function (params) {
                return {
                    phone: params.term,
                };
            },
            processResults: function (data) {
                var array = data.rows;
                // 使用map方法从数组中提取并只保留每个对象中的id和phone字段
                var idAndPhoneArray = array.map(function (item) {
                    return {
                        id: item.id,
                        text: item.phone + "--" + item.name+"["+ item.level + "] $" + item.balance,
                    };
                });
                return {
                    results: idAndPhoneArray
                };
            },
            cache: true
        },
        placeholder: '请输入电话搜索...',
        escapeMarkup: function (markup) {
            return markup;
        },
        minimumInputLength: 3,
    });

    //选中了之后的点击函数
    $('#customerId').on('select2:select', function (e) {
        // 处理自己的业务
         //获取选中项的值和标签文本
        var text =  e.params.data.text
        //截取到字符串里的[ ]中的内容赋值给lever
        var level = text.substring(text.indexOf("[")+1,text.indexOf("]"))
        //根据会员等级来计算折扣
        // 1000 0.88折  一级会员
        // 3000 0.8折
        // 5000 0.78折
        if (level==="0"||level===0){
            discount = 1
        }else if (level===1||level==="1"){
            discount = 0.88
        }else if (level===2||level==="2"){
            discount = 0.8
        }else if (level===3||level==="3"){
            discount = 0.78
        }
        // 触发数量计数框的change事件
        numberChange()
    });


    // ifChecked 触发时机：选框选中时触发
    $("input[name = description]").on('ifChecked', function (obj) {
        var id = $(this).attr('id');
        var numberInput = $('#' + id + '-descriptionNumber');
        // 移除数量计数框的disabled属性并设置值为1（添加延迟）
        numberInput.prop('disabled', false);
        numberInput.val(1);
        // 触发数量计数框的change事件
        numberInput.trigger('change');
    })

    //数量框监听函数
    function numberChange() {
        var newTotal = 0; // 初始化总金额为0
        var selectedLabels = []; // 初始化选中复选框的标签数组
        // 开始计算所有金额
        $('.check-box input[type="checkbox"]').each(function () {
            var checkbox = $(this);
            // 如果复选框被选中
            if (checkbox.is(':checked')) {
                //获取后面输入框,并改变状态
                var id = $(this).attr('id');
                var numberInput = $('#' + id + '-descriptionNumber');
                // 计算该复选框的值乘以数量计数框的值，并累加到总金额中
                newTotal += parseFloat(checkbox.val()) * parseFloat(numberInput.val());
                // 将选中复选框的标签值保存到数组中
                var labelText = checkbox.data('label') + "*" + numberInput.val() + "份("+discount+")"; // 获取自定义属性的值
                selectedLabels.push(labelText);
            }
        })

        // 更新总金额
        $('#total').text(parseFloat(newTotal).toFixed(2));// 显示保留两位小数的结果
        //更新折扣
        $('#discount').text(discount)
        //更新实际应付
        actualPay =  (parseFloat(newTotal).toFixed(2) * parseFloat(discount).toFixed(2)).toFixed(2)

        $('#actualPay').text(actualPay)
        //将账单业绩算在上面
        $('#amount').val(actualPay)

        $('#keyOne').val(selectedLabels.join(','))//将账单备注业绩算在上面

    }

    // ifUnchecked触发时机：选框取消选中时触发
    $("input[name = description]").on('ifUnchecked', function (obj) {
        //获取后面输入框,并改变状态
        var id = $(this).attr('id');
        var numberInput = $('#' + id + '-descriptionNumber');
        // 移除数量计数框的disabled属性并设置值为0
        numberInput.prop('disabled', true);
        numberInput.val(0);
        // 触发数量计数框的change事件
        numberInput.trigger('change');
    })


</script>
</body>
</html>